<template>
    <el-dialog title="PDF转换成WORD" :visible.sync="dialogFormVisible" :append-to-body="true" :before-close="handleClose"
        :close-on-click-modal="false" width="650px" top="20vh">
        <el-form label-width="0" class="demo-ruleForm" v-loading="loading" element-loading-text="正在转换中..."
            element-loading-background="rgba(0, 0, 0, 0.8)">
            <el-form-item prop="orderlist">
                <el-upload class="upload-demo" accept=".pdf" drag action="#" multiple ref="upload" :file-list="files"
                    :http-request="handleUpload" :on-exceed='handExceed' :on-remove="handleRemove"
                    :on-success='handFileSuccess' :before-remove="beforeRemove" :auto-upload="false" :limit="3">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处</div>
                    <div class="el-upload__tip" slot="tip">提示：一次只能上传3个文件，文件越大，转码越慢</div>
                </el-upload>
                <el-button size="small" @click="CancelUpload"><i class="
                    el-icon-close"></i>取 消</el-button>
                <el-button size="small" type="primary" @click="fileChange"><i class="el-icon-upload2"></i>立即上传</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import { none } from 'html-webpack-plugin/lib/chunksorter';

export default {
    name: 'PdfToWord',
    data() {
        return {
            dialogFormVisible: false,
            loading: false,
            files: []
        };
    },
    methods: {
        beforePdfUpload(file) {
            const isPDF = file.type === 'application/pdf';
            const isLt2M = file.size / 1024 / 1024 < 100;
            if (!isPDF) {
                this.$message.error('上传文件只能是 PDF 格式!');
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传文件大小不能超过 100MB!');
                return false
            }
            return isPDF && isLt2M;
        },
        handleUpload(raw) {
            this.files.push(raw.file);
            // console.log(files);
        },
        fileChange() {
            this.loading=true
            this.$refs.upload.submit() // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
            if(this.files.length<1){
                this.loading=false
                this.$message.error('请上传文件');
            }else{
                const isLt2M = this.files.every(file => file.size/ 1024 / 1024 < 100);
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 100MB!');
                    return false
                }else{
                    let formData = new FormData();
            this.files.forEach(function (file) {
                formData.append('file', file); // 因为要上传多个文件，所以需要遍历一下才行
                //不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
            })
            this.$axios.post('api/translate/pdftoword/', formData).then(res=>{
                // JSON.parse(res)
            if (res.data.code==2000) {
                this.$refs.upload.clearFiles();
                this.files = []
                this.loading=false;
                        this.$alert('转换完成，是否下载到本地？', '提示', {
                            confirmButtonText: '确定',
                            callback: action => {
                                this.$axios({
                                    method: "POST",
                                    url: "api/translate/getpdftoword/",
                                    data: res.data.data,
                                    responseType: 'blob' //返回是个文件
                                }).then(response => {
                                    this.downloadfile(response) //then直接下载，方法在下边
                                })
                            }
                        })

            } else {
                this.loading=false;
                this.$message.error(res.data.msg);
            }
            });
            
                }
            }
        },
        downloadfile(res) {
            var type_cus=''
            if(res.data.length>1){
                type_cus = 'application/msword'
            }else{
                type_cus =  'application/zip'
            }
            let blob = new Blob([res.data], { type: type_cus });//type是文件类，详情可以参阅blob文件类型
            // 创建新的URL并指向File对象或者Blob对象的地址
            const blobURL = window.URL.createObjectURL(blob)
            // 创建a标签，用于跳转至下载链接
            const tempLink = document.createElement('a')
            tempLink.style.display = 'none'
            tempLink.href = blobURL
            var fileName = decodeURI(res.headers['content-disposition'].split('=')[1])
            var newName = fileName.replace(new RegExp('"','g'),'')
            tempLink.setAttribute('download', newName)
            // 兼容：某些浏览器不支持HTML5的download属性
            if (typeof tempLink.download === 'undefined') {
                tempLink.setAttribute('target', '_blank')
            }
            // 挂载a标签
            document.body.appendChild(tempLink)
            tempLink.click()
            document.body.removeChild(tempLink)
            // 释放blob URL地址
            window.URL.revokeObjectURL(blobURL)
            this.dialogFormVisible = false
        },
        handExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        CancelUpload() {
            this.files = []
            this.$refs.upload.clearFiles();
        },
        handFileSuccess(file) {
            console.log(file);
            this.files = []
            this.$refs.upload.clearFiles();
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList);
            this.files = fileList
        },
        beforeRemove(file, fileList) {
            // console.log(file, fileList);
        },
        handleClose(){
            this.dialogFormVisible=false
        },
        CancelUpload(){
            this.dialogFormVisible=false
        }
    }
}
</script>

<style scoped lang="less">
/deep/ .el-upload {
    width: 100px;
}

/deep/ .el-upload .el-upload-dragger {
    width: 610px;
}
</style>